import os
from datetime import datetime

import pytest

from ifile import create_app
from ifile.db.sqlalchemy.session import get_session, get_engine
from ifile.db.sqlalchemy.api import Picture
from ifile.db.sqlalchemy.models import metadata, ifileGridFS
from config import config


@pytest.fixture(scope="session")
def app():
    _app = create_app(config['TESTING'])
    return _app


@pytest.fixture(scope="session")
def session(app):
    with app.app_context():
        engine = get_engine()
        metadata.create_all(engine)

        _session = get_session()
        yield _session

        db_path = os.path.join(os.getcwd(), 'test.db')

        if os.path.exists(db_path):
            os.remove(db_path)


@pytest.fixture
def picture_db():
    return Picture


@pytest.fixture
def gridfs(session):
    gridfs_params = {
        "uuid": "2cfaa656-fa61-48da-b60d-76cffdd1edad",
        "md5": "737722ac52de109e2f9affccff693283",
        "object_id": "5d623ccf86932734ecc30141",
        "chunk_size": 261120,
        "length": 14811136,
        "upload_date": datetime(2019, 8, 27, 21, 27, 39)
    }

    _gridfs = ifileGridFS(**gridfs_params)
    _gridfs.save(session=session)
    yield _gridfs

    session.query(ifileGridFS).filter(
        ifileGridFS.uuid == _gridfs.uuid).delete()
